<template>
  <el-card class="processing-progress">
    <template #header>
      <div class="card-header">
        <span><el-icon><Loading /></el-icon> 处理进度</span>
        <el-tag>{{ processingCount }} / {{ tasks.length }}</el-tag>
      </div>
    </template>

    <div class="task-list">
      <div
          v-for="task in tasks"
          :key="task.task_id"
          class="task-item"
      >
        <div class="task-info">
          <h4>{{ task.combination.output_name }}</h4>
          <div class="task-files">
            <span><el-icon><User /></el-icon> {{ task.combination.human.original_name }}</span>
            <span><el-icon><Picture /></el-icon> {{ task.combination.background.original_name }}</span>
          </div>
        </div>

        <div class="task-progress">
          <el-progress
              :percentage="taskStatus[task.task_id]?.progress || 0"
              :status="getProgressStatus(taskStatus[task.task_id]?.status)"
          />
          <div class="progress-text">
            {{ taskStatus[task.task_id]?.message || '等待处理...' }}
          </div>
        </div>

        <div class="task-actions">
          <el-button
              v-if="taskStatus[task.task_id]?.status === 'completed'"
              type="success"
              size="small"
              @click="downloadResult(task)"
          >
            下载
          </el-button>
          <el-button
              v-else-if="taskStatus[task.task_id]?.status === 'failed'"
              type="danger"
              size="small"
              @click="retryTask(task)"
          >
            重试
          </el-button>
        </div>
      </div>
    </div>

    <div class="summary" v-if="tasks.length > 0">
      <el-divider />
      <div class="summary-stats">
        <span>总进度: {{ overallProgress }}%</span>
        <span>成功: {{ completedCount }}</span>
        <span>失败: {{ failedCount }}</span>
        <span>处理中: {{ processingCount }}</span>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import api from '../api'

const props = defineProps({
  tasks: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['complete'])

// 响应式数据
const taskStatus = ref({})
let pollInterval = null

// 计算属性
const completedCount = computed(() => {
  return Object.values(taskStatus.value).filter(s => s.status === 'completed').length
})

const failedCount = computed(() => {
  return Object.values(taskStatus.value).filter(s => s.status === 'failed').length
})

const processingCount = computed(() => {
  return Object.values(taskStatus.value).filter(s => s.status === 'processing').length
})

const overallProgress = computed(() => {
  if (props.tasks.length === 0) return 0
  const totalProgress = Object.values(taskStatus.value).reduce((sum, status) => {
    return sum + (status.progress || 0)
  }, 0)
  return Math.round(totalProgress / props.tasks.length)
})

// 方法
const getProgressStatus = (status) => {
  const statusMap = {
    'completed': 'success',
    'failed': 'exception',
    'processing': ''
  }
  return statusMap[status] || ''
}

const pollTaskStatus = async () => {
  for (const task of props.tasks) {
    if (taskStatus.value[task.task_id]?.status === 'completed' ||
        taskStatus.value[task.task_id]?.status === 'failed') {
      continue
    }

    try {
      const result = await api.getTaskStatus(task.task_id)
      taskStatus.value[task.task_id] = result

      if (result.status === 'completed' || result.status === 'failed') {
        emit('complete', task.task_id)
      }
    } catch (error) {
      console.error(`查询任务状态失败: ${task.task_id}`, error)
    }
  }

  // 检查是否所有任务都完成
  const allDone = props.tasks.every(task => {
    const status = taskStatus.value[task.task_id]?.status
    return status === 'completed' || status === 'failed'
  })

  if (allDone && pollInterval) {
    clearInterval(pollInterval)
    pollInterval = null
  }
}

const downloadResult = (task) => {
  const status = taskStatus.value[task.task_id]
  if (status?.result_url) {
    api.downloadFile(status.result_url.split('/').pop())
  } else {
    ElMessage.warning('下载链接不存在')
  }
}

const retryTask = async (task) => {
  // 重新提交任务
  try {
    const data = {
      human_file_id: task.combination.human.file_id,
      background_file_id: task.combination.background.file_id,
      ...task.combination.params,
      output_name: task.combination.output_name
    }

    const result = await api.processVideo(data)
    if (result.success) {
      task.task_id = result.task_id
      taskStatus.value[task.task_id] = {
        status: 'processing',
        progress: 0,
        message: '重新处理中...'
      }
      ElMessage.success('已重新提交任务')
    }
  } catch (error) {
    ElMessage.error('重试失败')
  }
}

// 生命周期
onMounted(() => {
  // 初始化任务状态
  props.tasks.forEach(task => {
    taskStatus.value[task.task_id] = {
      status: 'processing',
      progress: 0,
      message: '准备处理...'
    }
  })

  // 立即查询一次
  pollTaskStatus()

  // 定时轮询
  pollInterval = setInterval(pollTaskStatus, 3000)
})

onUnmounted(() => {
  if (pollInterval) {
    clearInterval(pollInterval)
  }
})
</script>

<style lang="scss" scoped>
.processing-progress {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 500px;
  max-height: 600px;
  z-index: 1000;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    span {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }

  ::v-deep(.el-card__body) {
    max-height: 400px;
    overflow-y: auto;
  }
}

.task-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.task-item {
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;

  .task-info {
    margin-bottom: 10px;

    h4 {
      margin: 0 0 5px 0;
      font-size: 14px;
      font-weight: 500;
    }

    .task-files {
      display: flex;
      gap: 15px;
      font-size: 12px;
      color: #909399;

      span {
        display: flex;
        align-items: center;
        gap: 3px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        max-width: 200px;
      }
    }
  }

  .task-progress {
    margin-bottom: 10px;

    .progress-text {
      margin-top: 5px;
      font-size: 12px;
      color: #606266;
    }
  }

  .task-actions {
    display: flex;
    justify-content: flex-end;
  }
}

.summary {
  .summary-stats {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    color: #606266;
  }
}
</style>